/*
 *  Copyright 2013 National Institute of Advanced Industrial Science and Technology
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.sss.mapreduce.example;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Random;

import org.sss.client.DataPutter;
import org.sss.client.SssClient;
import org.sss.mapreduce.GroupID;
import org.sss.mapreduce.SssException;
import org.sss.mapreduce.datatype.PackableBytes;
import org.sss.mapreduce.datatype.PackableString;

public class GenBulkPoints {

  DataPutter<PackableString, PackableBytes> putter;
  GroupID groupId = null;
  Random rnd = new Random(0);

  public GenBulkPoints(SssClient client) throws RemoteException, NotBoundException,
      SssException {
    this.putter = DataPutter.create(client, PackableString.class,
        PackableBytes.class);
    this.groupId = putter.getOutputGroupID();
  }

  public byte[] genPoints(int numOfPoints, double xrange, double yrange)
      throws IOException {

    ByteArrayOutputStream os = new ByteArrayOutputStream(numOfPoints * 2 * 8);
    DataOutputStream dos = new DataOutputStream(os);

    for (int i = 0; i < numOfPoints; i++) {
      dos.writeDouble(rnd.nextDouble() * xrange);
      dos.writeDouble(rnd.nextDouble() * yrange);
    }
    dos.flush();
    dos.close();
    return os.toByteArray();
  }

  public void putBytes(String filename, byte[] bytes) throws Exception {
    putter.append(new PackableString(filename), new PackableBytes(bytes));
  }

  public void body(int numOfFiles, int numPoints) throws IOException, Exception {
    String key = "key";
    for (int i = 0; i < numOfFiles; i++) {
      putBytes(key + i, genPoints(numPoints, 100, 100));
    }
    putter.close();
    System.out.println("output data deployed - " + groupId.toString());
  }

  // NUM_OF_FILES NUM_POINTS
  public static void main(String[] args) throws Exception {
    SssClient client = new SssClient(args);

    String[] others = client.getArgs();

    int numOfFiles = Integer.parseInt(others[0]);
    int numPoints = Integer.parseInt(others[1]);

    new GenBulkPoints(client).body(numOfFiles, numPoints);
  }
}
